package co.chuangdian.oflauncher.widgets.system;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import cn.onekit.*;
import co.chuangdian.oflauncher.MainActivity;
import co.chuangdian.oflauncher.R;
import co.chuangdian.oflauncher.widgets.WidgetsFragment;
import uc.IconGridView;
import uc.IconGridViewAdapter;
import uc.IconInfo;
import uc.DragGridView.OnLongPressListener;

public class ContanctsWidget extends LinearLayout {
	private Activity context;
	private IconGridView iconGridView;
	private Bitmap bmp_head;

	public ContanctsWidget(Context context) {
		super(context);
		this.context = (Activity) context;
		MainActivity.contanctsWidgetFragment = this;
		init();
	}

	public OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// 跳转到联系人界面
			Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
			context.startActivityForResult(intent, 2);

		}
	};
	public OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

			long contacts;
			try {
				contacts = _contactIDs.getLong(position);
				// 跳转到拨打电话界面
				Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + getContactsNumber(contacts)));// 跳转到拨号界面，同时传递电话号码
				dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(dialIntent);
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
	};
	private View view;
	private ImageView addButton;

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		} else {
			Uri contactData = data.getData();
			@SuppressWarnings("deprecation")
			Cursor cursor = context.managedQuery(contactData, null, null, null, null);
			cursor.moveToFirst();
			setContactIds(cursor);
		}
	}

	// 获取联系人id
	public void setContactIds(Cursor cursor) {
		int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		int phoneNum = cursor.getInt(phoneColumn);
		if (phoneNum > 0) {
			// 获得联系人的ID号
			int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			long contactId = cursor.getLong(idColumn);
			if (!JSON.contains(_contactIDs, contactId)) {
				_contactIDs.put(contactId);
				UpdateData(_contactIDs);
			}
		}
	}

	/**
	 * 保存数据并更新
	 * 
	 * @param conid
	 */
	public void UpdateData(JSONArray contactsIds) {
		JSONObject systemwidgets = JSON.parse(CONFIG.get("systemwidgets"));
		try {
			systemwidgets.put("contacts", contactsIds);
			CONFIG.set("systemwidgets", systemwidgets);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		reloadIcons();
	}

	// 通过id获取头像
	private Bitmap getContactIcon(long id) {
		Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
		if (phone.moveToFirst()) {
			for (; !phone.isAfterLast(); phone.moveToNext()) {
				// 获得contact_id的Uri
				Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
				// 打开头像图片的InputStream
				InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
						uri);
				bmp_head = BitmapFactory.decodeStream(input);

			}

		}
		return bmp_head;
	}

	// 通过id获取号码
	private String getContactsNumber(long id) {
		String phoneNumber = null;
		Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
		if (phone.moveToFirst()) {
			for (; !phone.isAfterLast(); phone.moveToNext()) {
				int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
				// 获取电话号码
				phoneNumber = phone.getString(index);
			}

		}
		return phoneNumber;
	}

	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		reloadIcons();
	}

	// 通过id获取联系人名字
	private String getContactName(long id) {
		String name = this.getContactsNumber(id);
		Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
		if (phone.moveToFirst()) {
			for (; !phone.isAfterLast(); phone.moveToNext()) {
				int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
				// 获取电话号码
				name = phone.getString(index);
			}

		}
		return name;
	}

	IconGridViewAdapter adapter;

	private void init() {
		view = View.inflate(context, R.layout.widget_fastapp, this);
		addButton = (ImageView) view.findViewById(R.id.addButton);
		addButton.setOnClickListener(clickListener);
		iconGridView = (IconGridView) view.findViewById(R.id.iconGridView);
		iconGridView.parentScrollView = WidgetsFragment.scrollView;
		iconGridView.setOnItemClickListener(listener);
		iconGridView.setOnLongPressListener(longPressListener);
		adapter = new IconGridViewAdapter(getContext(), iconGridView);
		iconGridView.setAdapter(adapter);
	}

	JSONArray _contactIDs = new JSONArray();

	void reloadIcons() {
		List<IconInfo> icons = new ArrayList<IconInfo>();
		JSONObject systemwidgets = JSON.parse(CONFIG.get("systemwidgets"));
		_contactIDs = systemwidgets.optJSONArray("contacts");
		//
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		for (int i = 0; i < _contactIDs.length(); i++) {
			long contactID = _contactIDs.optLong(i);

			String name = getContactName(contactID);
			Bitmap image = getContactIcon(contactID);
			@SuppressWarnings("deprecation")
			Drawable icon = (image != null ? new BitmapDrawable(image) : null);
			icons.add(new IconInfo(String.valueOf(contactID), name, icon));

		}
		adapter.setData(icons);

		iconGridView.updateHeight();
	}

	private OnLongPressListener longPressListener = new OnLongPressListener() {

		@Override
		public void onLongPress(int index) {
			showUpdateDailog(index);
		}

	};

	private void showUpdateDailog(final int i) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("");
		builder.setMessage("是否移除？");
		builder.setPositiveButton("否", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();
			}
		});

		builder.setNegativeButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				_contactIDs.remove(i);
				UpdateData(_contactIDs);
			}
		});

		// 设置取消的监听, 用户点击返回键时会触发
		builder.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
			}
		});

		builder.show();
	}

	public void setVisible(boolean isShowing) {
		adapter.mini = !isShowing;
		iconGridView.updateHeight();
		adapter.notifyDataSetChanged();
	}
}
